<?php namespace App\Http\Controllers\Api\Admin;

use App\Activity;
use App\Admin;
use App\AnswerSheet;
use App\Banner;
use App\BooksChapter;
use App\BooksInfo;
use App\Classify;
use App\Http\Controllers\Controller;
use App\Http\Services\FileManager;
use App\Questions;
use App\RechargePackage;
use App\User;
use App\UserAnswer;
use App\UserAnswerDetail;
use App\UserInfo;
use App\VipRule;
use Auth;
use Illuminate\Http\Request;

class SystemController extends Controller
{
    public function setBanner(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $title   = $request->get('title');
        $linkUrl = $request->get('link_url');
        $sort    = $request->get('sort');
        $imgId   = $request->get('img_id');
        $id      = !is_null($request->get('id'))?$request->get('id'):0;

        $thatBanner = Banner::whereId(trim($id))->first();

        if(!$thatBanner)
            $thatBanner = new Banner();

        if(!is_null($title))$thatBanner->title = $title;
        if(!is_null($linkUrl))$thatBanner->link_url = $linkUrl;
        if(!is_null($sort))$thatBanner->sort = $sort;
        if(!is_null($imgId))$thatBanner->img_id = $imgId;
        $thatBanner->save();

        return response()->json(["level"=>"success","message"=>"添加或修改成功","data"=>$thatBanner]);
    }

    public function delBanner(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $id = !is_null($request->get('id'))?$request->get('id'):0;

        /** @var Banner $thatBanner */
        $thatBanner = Banner::whereId($id)->first();

        if(!$thatBanner)
            return response()->json(["level"=>"error","message"=>"该banner不存在！"]);

        $thatBanner->delete();

        return response()->json(["level"=>"success","message"=>"删除成功","data"=>$thatBanner]);
    }

    public function setAdmin(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $username = $request->get('username');
        $password = $request->get('password');
        $repass   = $request->get('repass');

        if($password != $repass)
            return response()->json(['level'=>'error','message' => '两次密码不一致！']);

        /** @var Admin $hasUser */
        $hasUser = Admin::whereUsername($username)->first();
        if($hasUser){
            return response()->json(['level'=>'error','message' => '当前管理员账号已存在']);
        }

        $thatAdmin = new Admin();
        $thatAdmin->username = $username;
        $thatAdmin->password = bcrypt($password);
        $thatAdmin->status = 2;
        $thatAdmin->save();

        return response()->json(['level'=>'success','message'=>'添加成功','data'=>$thatAdmin]);
    }

    public function delAdmin(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $id = !is_null($request->get('id'))?$request->get('id'):0;

        /** @var Admin $thatAdmin */
        $thatAdmin = Admin::whereId($id)->first();

        if(!$thatAdmin)
            return response()->json(["level"=>"error","message"=>"该管理员不存在！"]);

        if($thatAdmin->status == 1)
            return response()->json(["level"=>"error","message"=>"该管理员不能删除！"]);


        $thatAdmin->forceDelete();

        return response()->json(["level"=>"success","message"=>"删除成功","data"=>$thatAdmin]);
    }

    public function addClassify(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $name = $request->get("name");
        $sort = $request->get('sort');
        $id   = !is_null($request->get('id'))?$request->get('id'):0;

        $newClassify = Classify::whereId(trim($id))->first();

        if(!$newClassify)
            $newClassify = new Classify();

        if(!is_null($name))$newClassify->name = $name;
        if(!is_null($sort))$newClassify->sort = $sort;
        $newClassify->save();

        return response()->json(["level"=>"success","message"=>"添加或修改成功","data"=>$newClassify]);
    }

    public function delClassify(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $id = !is_null($request->get('id'))?$request->get('id'):0;
        $thatClassify =Classify::whereId($id)->first();

        if(!$thatClassify)
            return response()->json(["level"=>"error","message"=>"该分类不存在！"]);

        $thatClassify->delete();

        return response()->json(['level' => 'success','message' => '删除成功']);
    }

    public function getUserAnswerList(Request $request){
        $activityId = !is_null($request->get('activity_id')) ? $request->get('activity_id') : 1;
        $sort       = !is_null($request->get('sort')) ? $request->get('sort') : 0;
        $page        = !is_null($request->get('page')) ? $request->get('page') : 1;
        $limit       = !is_null($request->get('limit')) ? $request->get('limit') : 16;

        $arr = [
            'page' => $page,
            'limit' => $limit,
            'sort' => $sort
        ];

        /** @var UserAnswer $userAnswer */
        $userAnswerList = UserAnswer::whereNull('deleted_at')->where('status','<>',0);

        if($sort != 0){
            $answerSheetId = AnswerSheet::whereSort($sort)->lists('id');

            $userAnswerList->whereAsId($answerSheetId);
        }

        $arr['total'] = $userAnswerList->count();

        $userAnswerList = $userAnswerList->orderBy('submit_time','desc')->offset($limit * ($page - 1))->limit($limit)->get();
        if(count($userAnswerList) > 0){
            foreach($userAnswerList as $userAnswer){
                $userAnswer->realname  = '';
                $userAnswer->photo_url = '';
                $userAnswer->sort_name = '未知';

                /** @var UserInfo $thisUser */
                $thisUser = UserInfo::whereUserId($userAnswer->user_id)->first();
                if($thisUser){
                    $userAnswer->realname  = $thisUser->realname;
                    $userAnswer->photo_url = FileManager::getImgUrl($thisUser->photo_id);
                }

                if($userAnswer->status == 2){
                    $userAnswer->status_name = '已评分';
                }else{
                    $userAnswer->status_name = '未评分';
                }

                /** @var AnswerSheet $answerSheet */
                $answerSheet = AnswerSheet::whereId($userAnswer->as_id)->whereStatus(1)->first();
                if($answerSheet){
                    if($answerSheet->sort == 1){
                        $userAnswer->sort_name = '一轮答卷';
                    }elseif($answerSheet->sort == 2){
                        $userAnswer->sort_name = '二轮答卷';
                    }
                }
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $userAnswerList,'page_info' => $arr]);
    }

    public function setScore(Request $request){
        $userAnswerId = !is_null($request->get('id')) ? $request->get('id') : 0;
        $score        = !is_null($request->get('score')) ? $request->get('score') : 0;

        /** @var UserAnswer $userAnswer */
        $userAnswer = UserAnswer::whereId($userAnswerId)->first();
        if(!$userAnswer)
            return response()->json(['level' => 'error','message' => '用户未答题']);

        if($userAnswer->status == 2)
            return response()->json(['level' => 'error','message' => '已评分，请勿重复操作']);

        if(is_float($score))
            return response()->json(['level' => 'error','message' => '分数不能为小数']);

        if($score < 0){
            return response()->json(['level' => 'error','message' => '分数不能小于0']);
        }

        $userAnswer->score  = $score;
        $userAnswer->status = 2;
        $userAnswer->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $userAnswer]);
    }

    public function getUserQuestionAnswer(Request $request){
        $userAnswerId = !is_null($request->get('id')) ? $request->get('id') : 0;

        /** @var UserAnswer $userAnswer */
        $userAnswer = UserAnswer::whereId($userAnswerId)->first();
        if(!$userAnswer)
            return response()->json(['level' => 'error','message' => '用户未答题']);

        /** @var AnswerSheet $answerSheet */
        $answerSheet = AnswerSheet::whereId($userAnswer->as_id)->whereStatus(1)->first();
        if(!$answerSheet)
            return response()->json(['level' => 'error','message' => '答卷不存在']);

        $questionList = Questions::whereAsId($answerSheet->id)->whereStatus(1)->orderBy('sort','asc')->orderBy('created_at','desc')->get();
        if(count($questionList) > 0){
            foreach($questionList as $question){
                $question->user_answer = '';

                /** @var UserAnswerDetail $userAnswerDetail */
                $userAnswerDetail = UserAnswerDetail::whereUaId($userAnswer->id)->whereQId($question->id)->first();
                if($userAnswerDetail){
                    $question->user_answer = $userAnswerDetail->answer;
                }
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $questionList,'answer_sheet_title' => $answerSheet->title]);
    }

    public function getLeaderBoard(Request $request){
        $activityId = !is_null($request->get('activity_id')) ? $request->get('activity_id') : 1;
        $page        = !is_null($request->get('page')) ? $request->get('page') : 1;
        $limit       = !is_null($request->get('limit')) ? $request->get('limit') : 30;

        $arr = [
            'page' => $page,
            'limit' => $limit
        ];

        /** @var AnswerSheet $answerSheetTwo */
        $answerSheetTwo = AnswerSheet::whereActivityId($activityId)->whereSort(2)->whereStatus(1)->first();

        /** @var AnswerSheet $answerSheetOne */
        $answerSheetOne = AnswerSheet::whereActivityId($activityId)->whereSort(1)->whereStatus(1)->first();

        $data = [];
        if($answerSheetTwo && $answerSheetOne){
            if(strtotime($answerSheetOne->end_time) <= time() && strtotime($answerSheetTwo->end_time) > time()){
                $rank = 0;

                /** @var UserAnswer $userAnswerOne */
                $userAnswerOneList = UserAnswer::whereAsId($answerSheetOne->id)->whereStatus(2);

                $arr['total'] = $userAnswerOneList->count();

                $userAnswerOneList = $userAnswerOneList->orderBy('score','desc')->orderBy('submit_time','asc')->offset($limit * ($page - 1))->limit($limit)->get();
                if(count($userAnswerOneList) > 0){
                    foreach($userAnswerOneList as $userAnswerOne){
                        if($page > 1 && (($page - 1) * $limit + 1) > $rank){
                            $rank = ($page - 1) * $limit;
                        }

                        $rank += 1;

                        $userAnswerOne->phone = '';
                        $userAnswerOne->realname = '';
                        $userAnswerOne->photo_url = '';
                        $userAnswerOne->one_score = $userAnswerOne->score;
                        $userAnswerOne->two_score = '';
                        $userAnswerOne->rank = $rank;


                        /** @var User $thisUser */
                        $thisUser = User::whereId($userAnswerOne->user_id)->first();
                        if($thisUser){
                            $userAnswerOne->phone = $thisUser->phone;
                        }

                        /** @var UserInfo $thisUserInfo */
                        $thisUserInfo = UserInfo::whereUserId($userAnswerOne->user_id)->first();
                        if($thisUserInfo){
                            $userAnswerOne->realname = $thisUserInfo->realname;
                            $userAnswerOne->photo_url = FileManager::getImgUrl($thisUserInfo->photo_id);
                        }
                    }
                }

                $data = $userAnswerOneList;
            }elseif(strtotime($answerSheetTwo->end_time) <= time()){
                $userAnswerTwoUserIds = [];
                $rank = 0;

                /** @var UserAnswer $userAnswerTwo */
                $userAnswerTwoList = UserAnswer::whereAsId($answerSheetTwo->id)->whereStatus(2)->orderBy('score','desc')->orderBy('submit_time','asc')->take(30)->get();
                if(count($userAnswerTwoList) > 0){
                    foreach($userAnswerTwoList as $userAnswerTwo){
                        $rank += 1;

                        $userAnswerTwo->phone = '';
                        $userAnswerTwo->realname = '';
                        $userAnswerTwo->photo_url = '';
                        $userAnswerTwo->one_score = '';
                        $userAnswerTwo->rank = $rank;

                        /** @var UserAnswer $thisOneUserAnswer */
                        $thisOneUserAnswer = UserAnswer::whereUserId($userAnswerTwo->user_id)->whereAsId($answerSheetOne->id)->whereStatus(2)->first();
                        if($thisOneUserAnswer){
                            $userAnswerTwo->one_score = $thisOneUserAnswer->score;
                        }
                        $userAnswerTwo->two_score = $userAnswerTwo->score;

                        /** @var User $thisUser */
                        $thisUser = User::whereId($userAnswerTwo->user_id)->first();
                        if($thisUser){
                            $userAnswerTwo->phone = $thisUser->phone;
                        }

                        /** @var UserInfo $thisUserInfo */
                        $thisUserInfo = UserInfo::whereUserId($userAnswerTwo->user_id)->first();
                        if($thisUserInfo){
                            $userAnswerTwo->realname = $thisUserInfo->realname;
                            $userAnswerTwo->photo_url = FileManager::getImgUrl($thisUserInfo->photo_id);
                        }

                        array_push($userAnswerTwoUserIds,$userAnswerTwo->user_id);
                    }
                }

                if($page == 1){
                    $data =  $userAnswerTwoList;

                    /** @var UserAnswer $userAnswerOne */
                    $userAnswerOneList = UserAnswer::whereNotIn('user_id',$userAnswerTwoUserIds)->whereStatus(2)->whereAsId($answerSheetOne->id);

                    $total = $userAnswerOneList->count();
                }elseif($page > 1){
                    $page = $page - 1;

                    /** @var UserAnswer $userAnswerOne */
                    $userAnswerOneList = UserAnswer::whereNotIn('user_id',$userAnswerTwoUserIds)->whereStatus(2)->whereAsId($answerSheetOne->id);

                    $total = $userAnswerOneList->count();

                    $userAnswerOneList = $userAnswerOneList->orderBy('score','desc')->orderBy('submit_time','asc')->offset($limit * ($page - 1))->limit($limit)->get();
                    if(count($userAnswerOneList) > 0){
                        foreach($userAnswerOneList as $userAnswerOne){
                            if(($page * $limit + 1) > $rank){
                                $rank = $page * $limit;
                            }

                            $rank += 1;

                            $userAnswerOne->phone = '';
                            $userAnswerOne->realname = '';
                            $userAnswerOne->photo_url = '';
                            $userAnswerOne->one_score = $userAnswerOne->score;
                            $userAnswerOne->two_score = '';
                            $userAnswerOne->rank = $rank;

                            /** @var User $thisUser */
                            $thisUser = User::whereId($userAnswerOne->user_id)->first();
                            if($thisUser){
                                $userAnswerOne->phone = $thisUser->phone;
                            }

                            /** @var UserInfo $thisUserInfo */
                            $thisUserInfo = UserInfo::whereUserId($userAnswerOne->user_id)->first();
                            if($thisUserInfo){
                                $userAnswerOne->realname = $thisUserInfo->realname;
                                $userAnswerOne->photo_url = FileManager::getImgUrl($thisUserInfo->photo_id);
                            }
                        }
                    }
                    $data = $userAnswerOneList;
                }



                $arr['total'] = 30 + $total;
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $data,'page_info' => $arr]);
    }
}